/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: WakeRemote4J
 * Author: Harry Wu <harrywu304@gmail.com>
 *
 */
package org.shaitu.wakeremote4j.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.shaitu.wakeremote4j.AppContext;
import org.shaitu.wakeremote4j.HostBean;

/**
 * methods about packet
 * 
 * @author whx
 */
public class PacketUtil {
	
	/**
	 * construct magic power up packet
	 * @param destMac mac hex bytes
	 * @param ip 
	 * @param port 
	 * @return packet
	 * @throws UnknownHostException 
	 */
	private static DatagramPacket createPacket(byte[] destMac, String ip, int port) throws UnknownHostException{
        InetAddress destHost = InetAddress.getByName(ip);
        //construct packet data
        byte[] magicBytes = new byte[102];
        for(int i = 0; i < 6; i++){
        	magicBytes[i] = (byte)0xFF;
        }
        for(int i = 0; i < 16; i++){
            for(int j = 0; j < destMac.length; j++){
            	magicBytes[6+destMac.length*i+j] = destMac[j]; 
            }  
        }
        //create packet
        DatagramPacket dp = new DatagramPacket(magicBytes,magicBytes.length,destHost,port);
        return dp;
    }
    
    /**
     * send power up magic packet
     * @param mac
     * @param ip
     * @param port
     * @return
     */
    public static boolean sendWakeUpMessage(HostBean host){
    	DatagramSocket ds = null;
    	try{
    		//get input params
    		byte[] hexMac = host.getHexMac();
    		String ip = host.getIp();
    		int port = host.getPort();
    		if(StringUtil.isNullOrBlank(ip)){
    			ip = "255.255.255.255";    			
    		}
            if(port == 0){
                port = AppContext.PORT;
            }
    		//create magic packet
	        DatagramPacket dp = createPacket(hexMac,ip,port);
	        if(dp != null){
	        	//send udp packet
	            ds = new DatagramSocket();
	            ds.send(dp);
	            return true;
	        }
    	} catch(Exception e){
    		e.printStackTrace();
    	} finally {
    		if(ds != null){
    			ds.close();
    		}	
    	}
        return false;
    }
    
}
